package cn.edu.zut.soft.graduate.controller;

import cn.edu.zut.soft.basic.core.model.bo.CommonResult;
import cn.edu.zut.soft.graduate.core.model.Impl.Info;
import cn.edu.zut.soft.graduate.core.vo.LoginVO;
import cn.edu.zut.soft.graduate.userCenter.bo.IdentityBO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * Created by chuchuang on 16/10/24.
 */
@Controller
@RequestMapping("")
public class LoginController extends BaseController {

    @Resource
    private IdentityBO identityBO;

    @RequestMapping(value = "login",method = RequestMethod.POST)
    @ResponseBody
    public CommonResult login(HttpSession session, String u, String p) {
        LoginVO result = identityBO.identification(u, p);
        if (result!=null){
            if (result.getInfoList() != null) {
                for (Info info : result.getInfoList()) {
                    session.setAttribute(info.getType()+""+info.getKey(),info.getValue());
                }
                result.getInfoList().clear();
            }
            session.setAttribute("user", result);
            return CommonResult.successReturn(result);
        }
        return CommonResult.errorReturn("账号或密码错误");
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/";
    }

    @RequestMapping("/home")
    public String home(HttpSession session){
        LoginVO loginVO = (LoginVO) session.getAttribute("user");
        if (loginVO == null || loginVO.getRole() ==null) {
            return "redirect:/";
        }else {
            return "redirect:/"+loginVO.getRole();
        }
    }

    @RequestMapping(value = "login",method = RequestMethod.GET)
    public String index() {
        return "index";
    }


}
